<template>
  <div class="tradition_expenses">
    <el-row :gutter="20" class="gl_mb_20">
      <el-col :span="12">
        <!-- <el-row :gutter="10">
          <el-col :span="24" align="right" style="line-height: 36px;">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="openExpensesType">费用类型</el-button>
          </el-col>
        </el-row> -->
        <el-table class="expenses_table" :data="showTableData" :loading="showTableLoading" :show-header="false" size="mini" style="width: 100%;">
          <el-table-column :min-width="200">
            <template slot-scope="{ row }">
              <span class="form_name">{{ row.name }}：</span>
              <el-input v-model="row.amount" type="text" size="mini" class="gl_mr_5" style="width: calc(100% - 100px);" />
              <span>元</span>
            </template>
          </el-table-column>
          <el-table-column align="center" :width="150">
            <template v-if="row.chargeTypeCode === 'Entry'" slot-scope="{ row }">
              <span>兼项：</span>
              <el-input v-model="row.parameter" min="0" max="100" type="number" size="mini" class="gl_mr_5" style="width: calc(100% - 60px);" />
              <span>个</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="right" :width="90">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="submitExpenses(row)">确定</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="12">
        <el-table v-loading="tableLoading" :data="tableData" stripe size="mini" style="width: 100%;">
          <el-table-column prop="name" label="费用名称" :min-width="150" />
          <el-table-column label="金额（元）" align="center" :width="150">
            <template slot-scope="{ row }">
              <div style="line-height: 28px;">{{ row.amount && row.amount / 100 }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" :width="150">
            <template v-if="row.chargeTypeCode === 'Entry'" slot-scope="{ row }">
              <span>兼项：</span>
              <el-input v-model="row.parameter" min="0" max="100" type="number" size="mini" class="gl_mr_5" style="width: calc(100% - 60px);" @blur="changeParameter(row)" />
              <span>个</span>
            </template>
          </el-table-column>
          <el-table-column :label="$t('table.actions')" align="center" :width="100">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="openExpenses(row)"> {{ $t('table.edit') }} </el-button>
              <el-button size="mini" type="text" @click="deleteExpenses(row)">
                <span class="gl_color_error">{{ $t('table.delete') }}</span>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-row class="gl_pt_20">
      <el-col align="center">
        <el-button :loading="buLoading" size="mini" type="primary" @click="application()">应用</el-button>
      </el-col>
    </el-row>
    <!-- 新增费用类型 -->
    <el-dialog
      class="gl_dialog_TitleLine"
      width="520px"
      title="添加费用类型"
      :visible.sync="addExpeneseDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form
        ref="addExpeneseDialog"
        :model="api_POST_CompetitionChargeVO"
        label-width="80px"
        size="mini"
        :rules="api_POST_CompetitionChargeVO_Rules"
        @submit.native.prevent
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="费用名称" prop="name">
              <el-input v-model.trim="api_POST_CompetitionChargeVO.name" placeholder="请填写费用名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button size="mini" @click="addExpeneseDialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="addExpensesType">确 定</el-button>
      </div>
    </el-dialog>
    <edit-expenses ref="editExpenses" @refreshPage="getExpensesList()" />
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import editExpenses from './editExpenses';
import { Api_GET_CompetitionChargeQO, Api_POST_CompetitionChargeVO } from '@/lib/form/events';
import { Api_POST_CompetitionChargeVO_Rules } from '@/lib/validate/events';
import {
  api_PUT_CompetitionCategoryChargeCompetitionChargeType // 应用计费模式
} from '@/extend/api/game.js';
import {
  api_GET_EventsManagementCompetitionCharge,
  api_DELETE_EventsManagementCompetitionChargeId,
  api_POST_EventsManagementCompetitionCharge,
  api_PUT_EventsManagementCompetitionChargeId
} from '@/extend/api/gameswaggerApi/app';
import { CopyData } from '@/lib';
export default {
  name: 'Expenses',
  components: {
    editExpenses
  },
  data() {
    return {
      showTableLoading: false,
      tableLoading: false,
      buLoading: false,
      api_GET_CompetitionChargeQO: new Api_GET_CompetitionChargeQO(),
      api_POST_CompetitionChargeVO: new Api_POST_CompetitionChargeVO(),
      api_POST_CompetitionChargeVO_Rules: new Api_POST_CompetitionChargeVO_Rules(),
      showTableData: [],
      tableData: [],
      addExpeneseDialogVisible: false
    };
  },
  computed: {
    ...mapState({
      dict: state => state.dict.dict
    })
  },
  created() {
    this.showTableLoading = true;
    this.init();
    Promise.all([this.getDict(), this.getExpensesList()]).then(() => {
      this.handleLeftExpenses();
      this.showTableLoading = false;
    }, () => {
      this.showTableLoading = false;
    });
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    init() {
      this.gameId = this.$route.params.id;
      this.api_GET_CompetitionChargeQO = new Api_GET_CompetitionChargeQO();
      this.api_GET_CompetitionChargeQO.IncludeChargeType = true;
      this.api_GET_CompetitionChargeQO.competitionId = this.gameId;
    },
    // 获取费用列表
    getExpensesList() {
      return new Promise((resolve, reject) => {
        this.tableLoading = true;
        this.showTableLoading = true;
        api_GET_EventsManagementCompetitionCharge(this.api_GET_CompetitionChargeQO).then(res => {
          this.tableLoading = false;
          this.showTableLoading = false;
          this.tableData = res.items || [];
          this.handleLeftExpenses();
          resolve(res);
        }, () => {
          this.tableLoading = false;
          this.showTableLoading = false;
          this.$message({ type: 'error', message: '获取费用列表失败！' });
          reject();
        });
      });
    },
    // 删除
    deleteExpenses(expensesInfo) {
      this.$confirm(`您确定要删除该费用吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableLoading = true;
        api_DELETE_EventsManagementCompetitionChargeId(expensesInfo.id).then(() => {
          this.getExpensesList();
          this.$message({ type: 'success', message: '删除成功！' });
        }, error => {
          this.tableLoading = false;
          this.$message({ type: 'error', message: `删除失败！${error.error.message}` });
        });
      }).catch(() => {});
    },
    // 处理左侧显示的费用类型
    handleLeftExpenses() {
      if (!this.dict.competitionChargeType) return;
      const competitionChargeType = this.dict.competitionChargeType;
      const expeneseType = [];
      // 初始化字典
      for (let i = 0; i < competitionChargeType.length; i++) {
        const item = competitionChargeType[i];
        // 非自定义
        if (item.code === 'Custom') continue;
        const api_POST_CompetitionChargeVO = new Api_POST_CompetitionChargeVO();
        api_POST_CompetitionChargeVO.chargeTypeCode = item.code;
        api_POST_CompetitionChargeVO.name = item.value;
        expeneseType.push(api_POST_CompetitionChargeVO);
      }
      // 赋值回显
      const addExpeneseType = [];
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        for (let j = 0; j < expeneseType.length; j++) {
          const jtem = expeneseType[j];
          if (item.name === jtem.name) {
            CopyData(item, jtem);
            jtem.amount = jtem.amount && jtem.amount / 100;
            jtem.id = item.id;
            break;
          }
          if (j === expeneseType.length - 1) {
            const api_POST_CompetitionChargeVO = new Api_POST_CompetitionChargeVO();
            CopyData(item, api_POST_CompetitionChargeVO);
            api_POST_CompetitionChargeVO.amount = api_POST_CompetitionChargeVO.amount && api_POST_CompetitionChargeVO.amount / 100;
            api_POST_CompetitionChargeVO.id = item.id;
            addExpeneseType.push(api_POST_CompetitionChargeVO);
          }
        }
      }
      this.showTableData = expeneseType.concat(addExpeneseType);
    },
    openExpenses(expensesInfo) {
      this.$refs.editExpenses.open(expensesInfo);
    },
    // 打开费用类型
    openExpensesType() {
      this.api_POST_CompetitionChargeVO = new Api_POST_CompetitionChargeVO();
      this.api_POST_CompetitionChargeVO.chargeTypeCode = 'Custom';
      this.addExpeneseDialogVisible = true;
    },
    // 新增费用类型
    addExpensesType() {
      this.$refs.addExpeneseDialog.validate(valid => {
        if (!valid) return;
        // 判断是否重名
        for (let i = 0; i < this.showTableData.length; i++) {
          const item = this.showTableData[i];
          if (item.name === this.api_POST_CompetitionChargeVO.name) {
            this.$message({ type: 'error', message: '不能新增相同名称的费用类型！' });
            return;
          }
        }
        this.showTableData.push(this.api_POST_CompetitionChargeVO);
        this.addExpeneseDialogVisible = false;
      });
    },
    // 提交费用
    submitExpenses(expensesInfo) {
      console.log(expensesInfo);
      if (!expensesInfo.amount) {
        this.$message({ type: 'warning', message: '请输入金额！' });
        return;
      }
      // 报名费 如果兼项个数未填则提示必填
      if (expensesInfo.chargeTypeCode === 'Entry' && !expensesInfo.parameter) {
        this.$message({ type: 'warning', message: '请输入兼项个数！' });
        return;
      }
      expensesInfo.competitionId = this.gameId;
      const _api_POST_CompetitionChargeVO = JSON.parse(JSON.stringify(expensesInfo));
      _api_POST_CompetitionChargeVO.amount = Number(_api_POST_CompetitionChargeVO.amount) * 100;
      if (_api_POST_CompetitionChargeVO.id) {
        this.editExpenses(_api_POST_CompetitionChargeVO);
      } else {
        this.addExpenses(_api_POST_CompetitionChargeVO);
      }
    },
    // 兼项个数改变
    changeParameter(expensesInfo) {
      console.log(expensesInfo);
      const api_POST_CompetitionChargeVO = new Api_POST_CompetitionChargeVO();
      CopyData(expensesInfo, api_POST_CompetitionChargeVO);
      api_POST_CompetitionChargeVO.id = expensesInfo.id;
      api_POST_CompetitionChargeVO.competitionId = this.gameId;
      api_POST_CompetitionChargeVO.amount = Number(api_POST_CompetitionChargeVO.amount);
      // 报名费 如果兼项个数未填则提示必填
      if (api_POST_CompetitionChargeVO.chargeTypeCode === 'Entry' && !api_POST_CompetitionChargeVO.parameter) {
        this.$message({ type: 'warning', message: '请输入兼项个数！' });
        return;
      }
      this.editExpenses(api_POST_CompetitionChargeVO);
    },
    // 新增赛事费用
    addExpenses(api_POST_CompetitionChargeVO) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_POST_EventsManagementCompetitionCharge(api_POST_CompetitionChargeVO).then(res => {
          resolve(res);
          this.getExpensesList();
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '新增赛事费用失败！' + error.error.message });
        });
      });
    },
    // 编辑赛事费用
    editExpenses(api_POST_CompetitionChargeVO) {
      return new Promise((resolve, reject) => {
        this.loading = true;
        api_PUT_EventsManagementCompetitionChargeId(api_POST_CompetitionChargeVO.id, api_POST_CompetitionChargeVO).then(res => {
          this.getExpensesList();
          resolve(res);
        }, error => {
          reject(error);
          this.$message({ type: 'error', message: '编辑赛事费用失败！' + error.error.message });
        });
      });
    },
    // 应用计费模式
    application() {
      var that = this;
      that.buLoading = true;
      const form = {
        competitionId: this.gameId,
        chargeTypeCode: 'Tradition'
      };
      api_PUT_CompetitionCategoryChargeCompetitionChargeType(form).then(res => {
        that.$message({ type: 'success', message: '应用成功' });
        that.buLoading = false;
        that.$emit('refreshSetting');
      }, (error) => {
        that.buLoading = false;
        that.$message({ type: 'error', message: error.error.message });
      });
    }
  }
};
</script>
<style lang="scss">
.tradition_expenses {
  .expenses_table .form_name {
    display: inline-block;
    width: 80px;
  }
  .el-table, .el-table__body-wrapper {
    min-height: auto;
  }
}
</style>
